package gitwebtask

import (
	"cvevulner/cve-timed-task/db_models"
	"cvevulner/cve-timed-task/util"
	"cvevulner/models"
	"fmt"
	"github.com/antchfx/htmlquery"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
	"strings"
	"time"
)

func Handle() {
	ormModel := orm.NewOrm()
	url := "https://gitee.com/openeuler/community/tree/master/sig"
	doc, uErr := util.UrlToHTML(url)
	if uErr != nil {
		logs.Error(" util.UrlToHTML error:", uErr, url)
		return
	}

	type sig struct {
		sigName  string
		sigPage  string
		etherpad string
	}

	sigsList := make([]sig, 0, 100)
	for i := 3; ; i += 2 {
		node, err := htmlquery.QueryAll(doc, fmt.Sprintf("//div[@id='tree-slider']/div[%d]/div[1]/a/@title", i))
		if err != nil {
			logs.Error("htmlquery.QueryAll error:", err)
			continue
		}
		if len(node) == 0 {
			break
		}

		sigName := htmlquery.SelectAttr(node[0], "title")
		if sigName == "sigs.yaml" || sigName == "README.md" {
			break
		}

		logs.Info("open transaction")
		tranErr := ormModel.Begin()
		if tranErr != nil {
			logs.Error(" Open transaction error:", tranErr.Error())
			continue
		}
		_, err = db_models.GetOneGitRepoGroups(sigName, ormModel)
		if err != nil {
			if errors.Is(orm.ErrNoRows, err) {
				err = db_models.InsertOneGitRepoGroups(&models.GitRepoGroups{
					GroupName: sigName,
				}, ormModel)
				if err != nil {
					logs.Error("db_models.InsertOneGitRepoGroups error:", err.Error())
					tranErr = ormModel.Rollback()
					if tranErr != nil {
						logs.Error(" Rollback transaction error:", tranErr.Error())
					}
				}
			} else {
				logs.Error("db_models.InsertOneGitRepoGroups error:", err.Error())
				tranErr = ormModel.Rollback()
				if tranErr != nil {
					logs.Error(" Rollback transaction error:", tranErr.Error())
				}
			}
		} else {
			tranErr = ormModel.Commit()
			if tranErr != nil {
				logs.Error(" Commit transaction error:", tranErr.Error())
			}
		}

		sigPageNodes, hErr := htmlquery.QueryAll(doc, fmt.Sprintf("//div[@id='tree-slider']/div[%d]/div[1]/a/@href", i))
		if hErr != nil {
			logs.Warn("htmlquery.QueryAll error:", hErr)
			continue
		}
		sigPage := htmlquery.SelectAttr(sigPageNodes[0], "href")

		etherpad := fmt.Sprintf("https://etherpad.openeuler.org/p/%s-meetings", sigName)
		s := sig{
			sigName:  sigName,
			sigPage:  sigPage,
			etherpad: etherpad,
		}
		//Get the name, homepage and etherpad of all sigs
		sigsList = append(sigsList, s)
	}
	for _, s := range sigsList {
		gitRepoGroup, rErr := db_models.GetOneGitRepoGroups(s.sigName, ormModel)
		if rErr != nil {
			logs.Warn("db_models.GetOneGitRepoGroups error:", rErr.Error())
			continue
		}
		rErr = db_models.DeleteGitRepoMember(gitRepoGroup.GroupId, ormModel)
		if rErr != nil {
			logs.Warn("db_models.DeleteGitRepoMember error:", rErr.Error())
			continue
		}

		urlOWNERS := fmt.Sprintf("https://gitee.com/openeuler/community/blob/master/sig/%s/OWNERS", s.sigName)
		docOWNERS, mErr := util.UrlToHTML(urlOWNERS)
		if mErr != nil {
			logs.Error("util.UrlToHTML error:", mErr.Error(), url)
			continue
		}
		nodeOWNERS, aErr := htmlquery.QueryAll(docOWNERS, "//div[@class=\"line\"]/text()")
		if aErr != nil {
			logs.Error("htmlquery.QueryAll error:", aErr)
			continue
		}
		if len(nodeOWNERS) > 1 {
			for _, k := range nodeOWNERS[1:] {
				i := htmlquery.InnerText(k)
				mSplit := strings.Split(i, "-")
				maintainer := strings.TrimSpace(mSplit[len(mSplit)-1])
				giteRepoMember := &models.GiteRepoMember{
					GroupId:    gitRepoGroup.GroupId,
					MemberName: maintainer,
					MemberType: "Maintainer",
					CreateTime: time.Now().Format("2006-01-02 15:04:05"),
				}
				aErr = db_models.InsertOneGiteRepoMember(giteRepoMember, ormModel)
				if aErr != nil {
					logs.Error("db_models.InsertOneGiteRepoMember error:", aErr.Error())
					continue
				}
			}
		}
	}
}
